package com.example.spring.bean;

import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Component
public class MyBean implements BeanNameAware, InitializingBean, DisposableBean {

    @Autowired
    HisBean hisBean;
    @Value("${name}")
    private String name;
    @Value("#{20-2}")
    private Integer age;
    @Value("男")
    private String sex;

//    @Autowired
//    public MyBean(HisBean hisBean) {
//        this.hisBean = hisBean;
//    }


    public MyBean() {
        System.out.println("第一步：调用类的无参构造函数:" + name);
    }

    public HisBean getHisBean() {
        return hisBean;
    }

    @Autowired
    public void setHisBean(HisBean hisBean) {
        this.hisBean = hisBean;
        System.out.println("注入属性");
    }

    @PostConstruct
    public void init() {
        System.out.println("第四步：属性被设置之后，可以获取到属性:" + name + age + sex);
        System.out.println(this.hisBean);
    }

    @PreDestroy
    public void destory() {
        // 在销毁 Bean 之前执行的清理工作
        System.out.println("第八步：Performing pre-destroy cleanup for MyBean");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "MyBean{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                '}';
    }

    @Override
    public void setBeanName(String s) {
        System.out.println("第二步：获取到bean的名称为：" + s);
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("第九步：实现DisposableBean接口才会调用此方法destroy,可以获取属性：" + name + age + sex);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("第五步：通过此方法可以获取到已经注入的属性值：" + name + age + sex);
    }
}
